require('dotenv').config();
const express = require('express');
const cors = require('cors'); // 新增cors引用
const pool = require('./db');
const app = express();
const crypto = require('crypto');
const {
	uploadFileToFtp,
	deleteFileFromFtp
} = require('./ftpService');
const multer = require('multer');
const upload = multer({
	storage: multer.memoryStorage()
}); // 使用内存存储

// AES 加密函数
const encryptAES = (text) => {
	if (!process.env.ENCRYPTION_KEY || process.env.ENCRYPTION_KEY.length !== 64) {
		throw new Error('Invalid encryption key length. ENCRYPTION_KEY must be 64-character hex string' + process
			.env.ENCRYPTION_KEY.length);
	}
	const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex'); // 32字节
	const iv = crypto.randomBytes(16);
	const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
	let encrypted = cipher.update(text, 'utf8', 'hex');
	encrypted += cipher.final('hex');
	return iv.toString('hex') + ':' + encrypted;
};


const allowedOrigins = ['http://localhost:5173', 'http://localhost:3000', 'http://localhost:3001'];

// 新增CORS中间件
app.use((req, res, next) => {
	const origin = req.headers.origin;
	// 检查请求的源是否在允许列表中
	if (allowedOrigins.includes(origin)) {
		res.header('Access-Control-Allow-Origin', origin)
	}

	res.header('Access-Control-Allow-Credentials', 'true')
	res.header('Access-Control-Allow-Headers', 'Content-Type, token , logintype')
	next()
})

app.use(express.json());

// 空信息

// 新闻信息
app.get('/api/painterInfolist', async (req, res) => {
	res.json({
		code: 200,
		data: {}
	});
});


// 新闻信息
app.get('/api/news', async (req, res) => {
	try {
		const [rows] = await pool.query(
			'SELECT id, title, `describe`, url ,stars, backurl FROM news_module_info order by id desc'
		);

		const data = {
			code: 200,
			data: rows,
			message: 'success'
		}
		res.json(data);
	} catch (err) {
		console.error('数据库查询错误:', err);
		res.status(500).json({
			error: '服务器错误',
			details: err.message // 返回具体错误信息
		});
	}
});



app.get('/api/designWebsite', async (req, res) => {
	try {
		const color = req.query ? req.query.color : 'white'
		const [rows] = await pool.query(
			"SELECT id, webname, shortname, weburl, webimg, color_type, coverimg  FROM design_website_info where color_type='" +
			color + "' order by id asc")

		let newArray = []
		let anoArray = []
		let lastArray = []

		rows.forEach((item, index) => {
			if (index < 10) {
				newArray.push(item)
			} else if (index > 9 && index < 18) {
				anoArray.push(item)
			} else {
				lastArray.push(item)
			}
		})

		const data = {
			code: 200,
			data: {
				"data_arr": newArray,
				"ano_arr": anoArray,
				"special_arr": lastArray,
				"req": req.color
			},
			message: 'success'
		}
		res.json(data);
	} catch (err) {
		res.status(500).json({
			error: '服务器错误',
			details: err.message // 返回具体错误信息
		});
	}
});




// 走马灯
app.get('/api/website/getCarousel', async (req, res) => {
	try {
		const [rows] = await pool.query(
			'SELECT id, content_title, content_url , content_target FROM carousel_content_info where type = "website_nav" order by id desc'
		);

		const data = {
			code: 200,
			data: rows,
			message: 'success'
		}
		res.json(data);
	} catch (err) {
		res.status(500).json({
			code: 500,
			error: '服务器错误',
			details: err.message // 返回具体错误信息
		});
	}
});

// 插入一个新的内容到coding类型下
app.post('/api/website/insertNewWebsiteInfo', async (req, res) => { // 1. 修正方法为post
	try {
		const {
			speed,
			parentId,
			imgUrl,
			websiteUrl,
			title,
			type
		} = req.body;

		const [queryResult] = await pool.query(
			`INSERT INTO navigation_info 
            (speed, parentId, createTime, imgUrl, introduction, websiteUrl, title, type)
            SELECT ?, ?, NOW(), ?, ?, ?, ?, ?
            FROM DUAL 
            WHERE NOT EXISTS (
                SELECT 1 FROM navigation_info WHERE imgUrl = ?
            )`,
			[speed, parentId, imgUrl, req.body.introduction, websiteUrl, title, type, imgUrl]
		);

		if (queryResult.affectedRows === 0) {
			return res.status(400).json({
				code: 400,
				message: '该网址已收录'
			});
		}
		const data = {
			code: 200,
			data: {
				affectedRows: queryResult.affectedRows
			},
			message: 'success'
		}
		res.json(data);
	} catch (error) { // 3. 统一错误变量名
		console.error('数据库操作错误:', error); // 4. 增强日志记录
		res.status(500).json({
			code: 500,
			error: '服务器错误',
			details: error.message
		});
	}
});


// 从网络收集而来的网址
app.post('/api/website/insertWebsiteFromOnline', async (req, res) => {
	try {
		const {
			website,
			intro,
			type,
			parentId
		} = req.body;
		
		const [queryResult] = await pool.query(
			`INSERT INTO navigation_get_from_online 
		    (status, website, intro, type, parentId, createTime)
		    SELECT ?, ?, ?, ?, ?, NOW()
		    FROM DUAL 
		    WHERE NOT EXISTS (
		        SELECT 1 FROM navigation_info WHERE imgUrl = ?
		    )`,
			[1, website, intro, type, parentId, website]
		);
		if (queryResult.affectedRows === 0) {
			return res.status(400).json({
				code: 400,
				message: '该网址已收录'
			});
		}
		const data = {
			code: 200,
			data: {
				affectedRows: queryResult.affectedRows
			},
			message: 'success'
		}
		res.json(data);
	} catch (err) {
		res.status(500).json({
			code: 500,
			error: '服务器错误',
			details: err.message // 返回具体错误信息
		});
	}
});

// 关键字搜索网站
app.get('/api/website/searchWebsiteNav', async (req, res) => {
	const {
		keyword
	} = req.query;
	try {
		// 添加更详细的错误日志
		const [rows] = await pool.query(
			`SELECT A.title,A.id,A.parentId,A.speed,A.type,concat("/nav_targeturl_imgs/",B.fileType,"/",A.imgUrl) as imgAddrPlus,A.introduction,A.websiteUrl,B.cnName, B.enName, B.color FROM navigation_info  A inner join navigation_parent_info  B on A.parentId = B.id where A.introduction like '%` +
			keyword + `%' and A.imgUrl != '' order by  A.imgUrl`
		);

		const result = rows.map(item => {
			return {
				...item,
				imgAddr: item.parentId == '10235447' ? item.imgAddrPlus + '-compressed.png' : item
					.imgAddrPlus + '.png'
			}
		})

		const data = {
			code: 200,
			data: encryptAES(JSON.stringify(result)),
			message: 'success'
		}
		res.json(data);
	} catch (err) {
		res.status(500).json({
			error: '服务器错误',
			details: err.message // 返回具体错误信息
		});
	}
})



// 获取coding下的导航地址
app.get('/api/website/getCodingToolsList', async (req, res) => {
	try {
		// 添加更详细的错误日志
		const [rows] = await pool.query(
			'SELECT A.title,A.id,A.parentId,A.speed,A.type,concat("/nav_targeturl_imgs/",B.fileType,"/",A.imgUrl,"-compressed.png") as imgAddr,A.introduction,A.websiteUrl,B.cnName, B.enName, B.color FROM navigation_info  A inner join navigation_parent_info  B on A.parentId = B.id where A.parentId = "10235447" order by  A.imgUrl'
		);

		// 组件
		const componentList = rows.filter(item => {
			return item.type === 'Component-Style-design'
		})
		// 颜色
		const colorList = rows.filter(item => {
			return item.type === 'Color-Mix'
		})
		// 数据
		const dataList = rows.filter(item => {
			return item.type === 'Deal-With-Data'
		})
		// 页面
		const pageList = rows.filter(item => {
			return item.type === 'Page-UI'
		})

		const result = {
			componentList: encryptAES(JSON.stringify(componentList)),
			colorList: encryptAES(JSON.stringify(colorList)),
			dataList: encryptAES(JSON.stringify(dataList)),
			pageList: encryptAES(JSON.stringify(pageList))
		}
		const data = {
			code: 200,
			data: result,
			message: 'success'
		}
		res.json(data);
	} catch (err) {
		res.status(500).json({
			error: '服务器错误',
			details: err.message // 返回具体错误信息
		});
	}
});


// 获取所有导航地址
app.get('/api/website/getNavList', async (req, res) => {
	try {
		// 添加更详细的错误日志
		const [rows] = await pool.query(
			'SELECT A.title,A.id,A.parentId,A.speed,concat("/nav_targeturl_imgs/",B.fileType,"/",A.imgUrl,".png") as imgAddr,A.introduction,A.websiteUrl,B.cnName, B.enName, B.color FROM navigation_info  A inner join navigation_parent_info  B on A.parentId = B.id where A.speed > 1 and B.id != "10235447" order by A.parentId, A.imgUrl'
		);

		// 营销
		const marketList = rows.filter(item => {
			return item.parentId === 1254889
		})
		// 设计
		const designList = rows.filter(item => {
			return item.parentId === 2354879
		})
		// 工具
		const toolsList = rows.filter(item => {
			return item.parentId === 3254681
		})
		// 艺术
		const artistList = rows.filter(item => {
			return item.parentId === 4521557
		})
		// 任意
		const randomList = rows.filter(item => {
			return item.parentId === 5256974
		})
		// 想法
		const thinkingHoleList = rows.filter(item => {
			return item.parentId === 6324482
		})
		// 灵感
		const inspirationList = rows.filter(item => {
			return item.parentId === 7715236
		})
		// 素材
		const materialList = rows.filter(item => {
			return item.parentId === 8541233
		})
		// 娱乐
		const haveFunList = rows.filter(item => {
			return item.parentId === 9154783
		})
		const result = {
			testList: encryptAES(JSON.stringify([{
				title: 'svg',
				id: '123456789'
			}])),
			marketList: encryptAES(JSON.stringify(marketList)),
			designList: encryptAES(JSON.stringify(designList)),
			toolsList: encryptAES(JSON.stringify(toolsList)),
			artistList: encryptAES(JSON.stringify(artistList)),
			randomList: encryptAES(JSON.stringify(randomList)),
			thinkingHoleList: encryptAES(JSON.stringify(thinkingHoleList)),
			inspirationList: encryptAES(JSON.stringify(inspirationList)),
			materialList: encryptAES(JSON.stringify(materialList)),
			haveFunList: encryptAES(JSON.stringify(haveFunList))
		}
		const data = {
			code: 200,
			data: result,
			message: 'success'
		}
		res.json(data);
	} catch (err) {
		res.status(500).json({
			error: '服务器错误',
			details: err.message // 返回具体错误信息
		});
	}
});

// 上传接口
app.post('/api/website/uploadToFtp', upload.single('file'), async (req, res) => {
	try {
		if (!req.file) {
			return res.status(400).json({
				code: 400,
				message: '请选择要上传的文件'
			});
		}
		const originalName = req.file.originalname;
		// 构建远程路径，包括文件类型和时间戳
		const fileType = req.query.fileType
		const remotePath = `/nav_targeturl_imgs/${fileType}/${originalName}`;

		// 调用FTP上传服务
		const ftpResult = await uploadFileToFtp(req.file.buffer, remotePath);

		// 插入数据库
		const [insertResult] = await pool.query(
			'INSERT INTO ftp_save_img_info (img_name, ftp_position, create_time) VALUES (?, ?, NOW())',
			[originalName, remotePath]
		)

		res.json({
			code: 200,
			data: {
				filename: originalName,
				ftpPath: remotePath,
				fileSize: req.file.size,
			},
			message: '文件上传成功'
		});
	} catch (err) {
		res.status(500).json({
			code: 500,
			error: '上传失败',
			details: err.message
		});
	}
});


// 删除已经上传的图片
app.post('/api/website/deleteFileFromFtp', async (req, res) => {
	try {
		const {
			remotePath
		} = req.body;
		const ftpResult = await deleteFileFromFtp(remotePath);
		res.json({
			code: 200,
			data: {
				ftpPath: remotePath,
			},
			message: '文件已移除'
		});
	} catch (err) {
		res.status(500).json({
			code: 500,
			error: '删除失败',
			details: err.message
		});
	}
})

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
	console.log(`服务器运行在 http://localhost:${PORT}`);
});